package suncertify.util;

import java.util.ResourceBundle;
import java.util.PropertyResourceBundle;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.MessageFormat;

/**
 * This class provides text messages from static property file
 */
public class Messages {
    private static final String RESOURCE_PATH = "/message.properties";
    private static final String RESOURCE_ENC = "UTF-8";
    private static final Messages instance = new Messages();
    private static ResourceBundle bundle;

    private Messages() {
        try {
            InputStream resource = Messages.class.getResourceAsStream(RESOURCE_PATH);
            if (resource != null) {
                Reader reader = new InputStreamReader(resource, RESOURCE_ENC);
                bundle = new PropertyResourceBundle(reader);
                reader.close();
            } else {
                System.out.println("resources is not loaded");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * returns instance
     * @return messages object
     */
    public static Messages getInstance() {
        return instance;
    }

    /**
     * returns formatted string value of specified property
     * @param key property key
     * @param data data for for property value format
     * @return if property is found, returns formatted string value, else return a last word from dot separated key
     */
    public String get(String key, Object... data) {
        String msg = bundle != null ? bundle.getString(key) : key.substring(key.lastIndexOf('.') + 1);
        if (data != null && data.length > 0) {
            msg = MessageFormat.format(msg, data);
        }
        return msg;
    }
}
